package com.demo.hdfs;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.log4j.Logger;
/**
 * $HADOOP_HOME/sbin/start-dfs.sh
 */
public class HDFSDemo {
	public static final Logger log = Logger.getLogger(HDFSDemo.class);
	
	public void hdfsConnection(String uri) throws IOException {
		Configuration config = new Configuration();
		FileSystem fs = FileSystem.get(URI.create(uri), config);

		String baseUserPath = "/users/hadoop";

		// 列出hdfs上/user/fkong/目录下的所有文件和目录
		FileStatus[] statuses = fs.listStatus(new Path(baseUserPath));
		for (FileStatus status : statuses) {
			log.info(status);
		}
		//System.err.println(System.getProperty("hadoop.home.dir"));
		log.info(System.getenv("HADOOP_HOME"));
		// 在hdfs的/user/fkong目录下创建一个文件，并写入一行文本
		FSDataOutputStream os = fs.create(new Path(baseUserPath+"/test2.txt"));
		os.write("Hello World!".getBytes());
		os.flush();
		os.close();

		// 显示在hdfs的/user/fkong下指定文件的内容
		InputStream is = fs.open(new Path(baseUserPath+"/test2.txt"));
		IOUtils.copyBytes(is, System.out, 1024, true);
	}
	
	public static void main(String[] args) throws IOException {
		String uri = "hdfs://127.0.0.1:9000/";
		//System.setProperty("hadoop.home.dir", "/home/hadoop/hadoop-2.6.5");
		HDFSDemo demo = new HDFSDemo();
		demo.hdfsConnection(uri);
	}

}
